#include "module_path.h"
#include <string.h>
#ifdef WIN32
#include <windows.h>
#else
#include <sys/times.h>
#include <sys/time.h>
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
#endif

std::string ApplicationInfo::getApplicationPath() {
    std::string execPath("./");
    char szFileName[MAX_PATH] = {0};
    char szProcessName[MAX_PATH] = {0};
    if (GetModulePath(szFileName, szProcessName, MAX_PATH) < 0) {
        fprintf(stderr, "get running path failed\n");    
    }
    execPath = szFileName;
    return execPath;
}

std::string ApplicationInfo::getApplicationName() {
    std::string execName;
    char szFileName[MAX_PATH] = {0};
    char szProcessName[MAX_PATH] = {0};
    if (GetModulePath(szFileName, szProcessName, MAX_PATH) < 0) {
        fprintf(stderr, "get running path failed\n");    
    }
    execName = szProcessName;
    return execName;
}

size_t ApplicationInfo::GetModulePath(char* processdir, char* processname, size_t len)
{
#ifdef WIN32
    char szPath[512] = { 0 };
    GetModuleFileName(NULL, szPath, sizeof(szPath) - 1);
    strcpy_s(processdir, MAX_PATH, szPath);
    size_t dirLen = strlen(processdir);
    size_t nIndex(dirLen); 
    while (nIndex > 0 && processdir[nIndex - 1] != '\\') nIndex--;
    char* pProcessName = processdir + nIndex;

    // use application name without suffix
    size_t dotIndex(dirLen);
    while (dotIndex > nIndex && processdir[dotIndex - 1] != '.') dotIndex--;
    int nameLen = dotIndex - nIndex - 1;
    strncpy_s(processname, MAX_PATH, pProcessName, nameLen);
    *pProcessName = '\0';
    //strcpy_s(processname, MAX_PATH, pProcessName);
    return nIndex;
#else
    char* path_end;
    if (readlink("/proc/self/exe", processdir, len) <= 0) return -1;
    path_end = strrchr(processdir, '/');
    if (path_end == NULL) return -1;
    ++path_end;
    strcpy(processname, path_end);
    *path_end = '\0';
    return (size_t)(path_end - processdir);
#endif
}
